<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 自定义组件，标题 -->
      <PageTitle :show-before="true">
        <template v-slot:before>
          <h2>{{ $t('route.newsContent') }}</h2>
        </template>
        <template v-slot:after>
          <el-button class="filter-item" size="medium" style="margin-left: 10px;" type="primary" icon="el-icon-edit" :disabled="!checkPermission('newsContent-add')" @click="addOrEidt('add',0)">{{ $t('button.add') }}</el-button>
        </template>
      </PageTitle>
      <!-- 搜索筛选 -->
      <el-row :gutter="20" style="margin-top:20px">
        <el-col :span="4">
          <el-input v-model="query.name" type="text" :placeholder="$t('table.title')" />
        </el-col>
        <el-col :span="5">
          <el-select v-model.number="query.cid" :placeholder="$t('table.selectThe')+$t('route.newsCate')" style="width: 100%;" clearable @clear="clearCate">
            <el-option-group v-for="(item,index) in cateList" :key="index" :label="item.name" :value="item.id">
              <el-option v-for="(item1,index1) in item.children" :key="index1" :label="item1.name" :value="item1.id" />
            </el-option-group>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model.number="query.status" :placeholder="$t('table.selectThe')+$t('table.state')" clearable @clear="clearStatus">
            <el-option v-for="(item,index) in statusData" :key="index" :label="item.value" :value="item.id" />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" icon="el-icon-search" @click="search">{{ $t('button.search') }}</el-button>
        </el-col>
      </el-row>
      <!-- 数据表 -->
      <el-table v-loading="downloadLoading" tooltip-effect="dark" border :data="list" max-height="650px" style="margin-top: 20px;" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="ID" prop="id" sortable="custom" width="60" />
        <el-table-column prop="pic" :label="$t('table.CatePic')">
          <template slot-scope="{row}">
            <div class="table-img"><img :src="row.pic" width="100%"></div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.title')" prop="name" width="200" />
        <el-table-column :label="$t('table.ShopCate')" prop="name">
          <template slot-scope="{row}">
            {{ row.cate_name }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.readcount')" prop="readcount" />
        <el-table-column :label="$t('table.state')" prop="status" width="120">
          <template slot-scope="{row}">
            <el-tag :type="row.status|statusFilter">
              {{ row.status|formatEmployment }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" :label="$t('table.sort')" width="250">
          <template slot-scope="{row}">
            <template v-if="row.isedit">
              <el-input v-model="row.sort" class="edit-input" size="small" style="width: 50%;" />
              <el-button
                style="margin-left: 10px;"
                class="cancel-btn"
                size="small"
                icon="el-icon-refresh"
                type="warning"
                @click="confirmEdit(row)"
              >
                {{ $t('button.confirm') }}
              </el-button>
            </template>
            <span v-else>{{ row.sort }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.creationTime')" prop="createtime" width="160">
          <template slot-scope="{row}">
            {{ row.createtime|timeStanp }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" align="center" width="260" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button icon="el-icon-edit" type="primary" size="mini" :disabled="!checkPermission('newsContent-edit')" @click="addOrEidt('edit',row)">{{ $t('button.edit') }}</el-button>
            <el-button v-if="row.isedit" type="warning" size="mini" @click="cancelEdit(row)">
              {{ $t('button.cancel') }}
            </el-button>
            <el-button v-else type="warning" size="mini" :disabled="!checkPermission('newsContent-set')" @click="paixu(row)">
              {{ $t('table.sort') }}
            </el-button>
            <el-button icon="el-icon-delete" type="dang er" size="mini" :disabled="!checkPermission('newsContent-del')" @click="delData(row.id)">{{ $t('button.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" align="middle" style="margin-top:20px">
        <el-pagination background layout="total,prev,pager,next" :total="count" :page-size="query.limit" :current-page="query.page" @current-change="changPage" />
      </el-row>
    </div>
    <!-- 添加 -->
    <el-dialog :title="dialogTitle" :visible="showDialog" width="70%" top="40px" @opened="openDialog" @close="btnCanle">
      <div class="shopOrder-dialog">
        <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="220px">
          <el-form-item :label="$t('table.title')" prop="name">
            <el-input v-model="formData.name" :placeholder="$t('table.enterThe')+' '+$t('table.title')" style="width:50%" />
          </el-form-item>
          <el-form-item :label="$t('table.subtitle')" prop="subname">
            <el-input v-model="formData.subname" :placeholder="$t('table.enterThe')+' '+$t('table.subtitle')" style="width:50%" />
          </el-form-item>
          <el-form-item :label="$t('table.zuozhe')" prop="author">
            <el-input v-model="formData.author" :placeholder="$t('table.enterThe')+' '+$t('table.zuozhe')" style="width:50%" />
          </el-form-item>
          <el-form-item :label="$t('table.images')" prop="pic">
            <ImageUpload ref="staffPhoto" />
          </el-form-item>
          <el-form-item :label="$t('route.newsCate')">
            <el-select v-model="cid" :multiple="true" :multiple-limit="1" :placeholder="$t('table.selectThe')+' '+$t('route.newsCate')" style="width: 80%;">
              <el-option-group v-for="(item,index) in cateList" :key="index" :label="item.name" :value="item.id">
                <el-option v-for="(item1,index1) in item.children" :key="index1" :label="item1.name" :value="item1.id" />
              </el-option-group>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('table.readcount')">
            <el-input v-model.number="formData.readcount" style="width:10%" />
          </el-form-item>

          <el-form-item :label="$t('table.state')" prop="status">
            <el-select v-model.number="formData.status" :placeholder="$t('table.selectThe')+' '+$t('table.state')">
              <template v-for="(item,index) in statusData">
                <el-option v-if="item.id!==9" :key="index" :label="item.value" :value="item.id" />
              </template>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('table.article_Content')">
            <RichText ref="child" :values="formData.content" />
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="btnCanle">{{ $t('button.cancel') }}</el-button>
        <el-button type="primary" @click="btnOk">{{ $t('button.confirm') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { getArticleList, addArticle, delArticle, sortArticle, getArticleCateList } from '@/api/user'
import user from '@/store/modules/user'
import { tranListTotreeDatCate, ArrNumne } from '@/utils'
export default ({
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: [],
      downloadLoading: false,
      statusData: [{
        id: 1,
        value: this.$t('table.show')
      },
      {
        id: 2,
        value: this.$t('table.hide')
      },
      {
        id: 9,
        value: this.$t('table.all')
      }],
      cateList: [],
      query: {
        id: undefined,
        name: '',
        aid: 1,
        cid: undefined,
        bid: undefined,
        status: 9,
        page: 1,
        limit: 10
      },
      cid: [],
      count: 0,
      dialogTitle: this.$t('button.add'),
      formData: {
        id: undefined,
        aid: 1,
        bid: undefined,
        cid: '',
        name: '',
        subname: '',
        pic: '',
        readcount: 0,
        content: '',
        status: undefined,
        author: ''
      },
      rules: {
        name: [{ required: true, message: this.$t('table.name') + this.$t('prompt.noEmpty'), trigger: 'blur' }],
        status: [{ required: true, message: this.$t('table.state') + this.$t('prompt.noEmpty'), trigger: 'blur' }]
      },
      showDialog: false
    }
  },
  created() {
    // 获取userid
    this.query.bid = parseFloat(user.state.userInfo.bid)
    this.formData.bid = parseFloat(user.state.userInfo.bid)
    this.getBusinessCateList()
    this.getShopCate()
  },
  methods: {
    // 获取商户分了列表
    async getBusinessCateList() {
      this.downloadLoading = true
      const { count, list } = await getArticleList(this.query)
      this.count = count
      // 给数组对象使用map循环添加新属性
      if (count > 0) {
        const lists = list.map((item, index) => {
          return Object.assign(item, { isedit: false })
        })
        this.list = lists
      } else {
        this.list = list
      }

      this.downloadLoading = false
    },
    // 获取分类列表
    async getShopCate() {
      const query = {
        id: undefined,
        bid: parseFloat(user.state.userInfo.bid),
        aid: 1,
        page: 1,
        limit: 100
      }
      const { list } = await getArticleCateList(query)
      // 调用自定义的树状数组函数，处理获取的数组
      this.cateList = tranListTotreeDatCate(list, 0)
    },
    // 点击展开新增修改
    addOrEidt(type, row) {
      if (type === 'add') {
        this.dialogTitle = this.$t('button.add')
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      } else if (type === 'edit') {
        console.log(row)
        this.dialogTitle = this.$t('button.edit')
        this.formData.id = row.id
        this.formData.name = row.name
        this.formData.subname = row.subname
        this.formData.status = row.status
        this.formData.pic = row.pic
        this.formData.sort = row.sort
        this.formData.readcount = row.readcount
        this.formData.content = row.content
        this.formData.author = row.author
        this.formData.content = row.content
        if (row.cid) {
          const cid = row.cid.toString()
          this.cid = ArrNumne(cid)
        }
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      }
    },
    // 点击确定时
    async btnOk() {
      try {
        // 校验整个表单
        await this.$refs.ruleForm.validate()
        // 读取上传组件的数据
        const fileList = this.$refs.staffPhoto.fileList
        // 循环判断是否已经完成全部上传
        if (fileList.some(item => !item.upload)) {
          //  如果此时去找 upload为false的图片 找到了说明 有图片还没有上传完成
          this.$message.warning(this.$t('prompt.noImage'))
          return
        }
        this.formData = { ...this.formData, pic: fileList && fileList.length ? fileList[0].url : '' }
        const cid = this.cid.toString(',')
        this.formData.cid = parseFloat(cid)
        // 获取富文本编辑内容
        this.formData.content = this.$refs.child.getVal()
        // 调用新增接口
        await addArticle(this.formData)
        // 更新数据
        this.getBusinessCateList()
        this.btnCanle()
        this.$message.success(this.$t('prompt.success'))
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 删除
    async delData(e) {
      const data = {
        id: e
      }
      try {
        await this.$confirm(this.$t('prompt.deleteit'))
        await delArticle(data)
        this.getBusinessCateList()
        this.$message.success(this.$t('prompt.deletesuccess'))
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 保存选择对象
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 取消重置原来的数据
    btnCanle() {
      this.formData = {
        id: undefined,
        aid: 1,
        bid: undefined,
        cid: '',
        name: '',
        subname: '',
        pic: '',
        readcount: 0,
        content: '',
        status: undefined,
        author: ''
      }
      this.cid = []
      this.$refs.staffPhoto.fileList = []
      this.$refs.child.content = ''
      this.$refs.ruleForm.clearValidate()// 重置校验结果
      this.showDialog = false
    },
    // 点击排序
    paixu(row) {
      row.isedit = true
    },
    // 取消排序
    cancelEdit(row) {
      row.isedit = false
    },
    // 确认排序
    async confirmEdit(row) {
      const data = {
        id: row.id,
        sort: parseInt(row.sort)
      }
      row.isedit = false
      try {
        await sortArticle(data)
        this.$message.success(this.$t('prompt.paixuSuccess'))
        this.getBusinessCateList()
      } catch (error) {
        this.$message.error(this.$t('prompt.failed'))
      }
    },
    // 搜索
    search() {
      this.query.page = 1
      this.getBusinessCateList()
    },
    // 分页
    changPage(newPage) {
      this.query.page = newPage
      this.getBusinessCateList()
    },
    openDialog() {
      // 判断有icon的数据
      if (this.formData.pic) {
        // 这里我们赋值，同时需要给赋值的地址一个标记 upload: true
        this.$refs.staffPhoto.fileList = [{ url: this.formData.pic, upload: true }]
      }

      if (this.formData.content) {
        this.$refs.child.content = this.formData.content
      }
    },
    clearStatus() {
      this.query.status = 9
    },
    clearCate() {
      this.query.cid = undefined
    }
  }
})
</script>
<style scoped lang="scss">
.shopGoods-item{
  display: flex;
  margin-bottom: 15px;
  .shopGoos_img{
    width: 80px;
    margin-right: 10px;
  }
  .shopGoos_wen{
    width: 200px;
    font-size: 12px;
    line-height: 18px;
    p{
      margin: 0;
    }
  }
  .goodsPrice{
    color: #f60;
    margin-top: 20px;
  }
}
.address-box{
  display: flex;
  align-items: center;
  .address-icon{
    width: 30px;
    margin-right: 20px;
  }
  .address-wen{
    display: flex;
    align-items: center;
    h1{
      font-size: 16px;
      margin-right: 10px;
    }
  }
  .address-area{
    p{
      margin: 0;
    }
  }
}
.shop-item{
  display: flex;
  margin-bottom: 20px;
  .shop-left{
    width: 100px;
    margin-right: 20px;
  }
  .shop-right{
    width:500px;
    p{
      margin: 0;
    }
    .goodsPrice{
      color: #f60;
      margin-top: 10px;
    }
  }
}
.order_information{
  padding-left: 0;
  margin: 0;
  li{
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    border-bottom: 1px solid #f2f2f2;
    padding:0 0 15px 0;
    .information-right{
      display: flex;
      justify-content: right;
      align-items: center;
      p{
        margin: 0;
      }
      .information-img{
        width: 40px;
        margin-right: 10px;
      }
    }

  }
}
.shopOrder-dialog{
  height: auto;
  max-height: 750px;
  overflow-y: auto;
}
.shopOrder-dialog::-webkit-scrollbar{display:none}
.color-red{
  color: #f60;
}
.form-pic-box{
  display: flex;
  margin-top: 20px;
  .formPic{
    margin-right: 10px;
  }
}
.ljm-table{
  thead{
    tr{
      background-color: #f2f2f2;
      th{
        border-width: 1px;
        border-style: solid;
        border-color: #e6e6e6;
        position: relative;
        padding: 9px 15px;
        min-height: 20px;
        line-height: 20px;
        font-size: 14px;
        text-align: left;
      }
    }
  }
  tbody{
    tr{
      margin-top: -1px;
      td{
        position: relative;
        padding: 9px 15px;
        min-height: 20px;
        line-height: 20px;
        font-size: 14px;
        border-width: 1px;
        border-style: solid;
        border-color: #e6e6e6;
        .layui-input{
          display: inline;
          height: 30px;
          padding-left: 10px;
          line-height: 1.3;
          border-width: 1px;
          border-style: solid;
          background-color: #fff;
          border-radius: 2px;
          border-color: #e6e6e6;
        }
        div{
          margin: 5px 0px;
          .layui-btn-sm{
            height: 30px;
            line-height: 30px;
            padding: 0 10px;
            font-size: 12px;
            margin-left: 5px;
          }
          .layui-btn-primary{
            border: 1px solid #C9C9C9;
            background-color: #fff;
            color: #555;
          }
          .layui-btn {
              display: inline-block;
              white-space: nowrap;
              text-align: center;
              border-radius: 2px;
              cursor: pointer;
          }
        }
      }
    }
  }
}
.Ggname-prompt{
  margin-top: 10px;
  p{
    font-size: 12px;
    color: #999;
    line-height: 22px;
    margin: 0 0;
  }
}
.shopOrder-dialog{
  height: auto;
  max-height: 750px;
  overflow-y: auto;
}
.tip_ljm{
  font-size: 12px;
    color: #999;
    line-height: 22px;
    margin-left: 10px;
}
.stokForm{
  display: flex;
  p{
    margin: 0 5px 0px 5px;
  }
}
.form-p{
  color: #f60;
  margin: 0;
}
</style>
